package net.cohoivang.core;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

import net.cohoivang.web.OurConnection;

public class ProfileCompany {
	private static ProfileCompany instance;
	private ProfileCompany() {}
	
	private final LinkedList<Sector> allSector = new LinkedList<Sector>();
	private final HashMap<Integer, Sector> sectorMap = new HashMap<Integer, Sector>();
	
	private final LinkedList<Industry> allIndustry = new LinkedList<Industry>();
	private final HashMap<Integer, Industry> industryMap = new HashMap<Integer, Industry>();
	
	private final HashMap<Integer, Company> companyMap = new HashMap<Integer, Company>();
	
		
	public LinkedList<Sector> getAllSector() {
		return allSector;
	}

	public LinkedList<Industry> getAllIndustry() {
		return allIndustry;
	}

	public static void initialize(OurConnection connection) throws SQLException {
		instance = new ProfileCompany();
		ProfileDatabase.initialize(connection);
		ProfileDatabase.getInstance().loadAllSector();
		ProfileDatabase.getInstance().loadAllIndustry();
		ProfileDatabase.getInstance().loadAllCompany();
	}
	
	public Company createCompany(int industryId, String legalName, String englishName) {
		Industry industry = findIndustry(industryId);
		Company company = industry.createCompany(legalName, englishName);
		companyMap.put(company.companyId, company);
		return company;
	}
		
	public Sector createSector(int sectorId, String sectorName) {
		Sector sector = new Sector(sectorId, sectorName);
		allSector.add(sector);
		sectorMap.put(sector.sectorId, sector);
		return sector;
	}
	
	public Industry findIndustry(int industryId) {
		return industryMap.get(industryId);
	}
	
	public Sector findSector(int sectorId) {
		return sectorMap.get(sectorId);
	}
	
	public Industry createIndustry(int sectorId, int industryId, String industryName) {
		Sector sector = findSector(sectorId);
		Industry industry = sector.createIndustry(industryId, industryName);		
		allIndustry.add(industry);
		industryMap.put(industryId, industry);
		return industry;
	}
	
	public Company findCompany(int companyId) {
		return companyMap.get(companyId);
	}
	
	public ArrayList<Company> getAllCompany() {
		synchronized (companyMap) {
			return new ArrayList<Company>(companyMap.values());
		}
	}
	
	
	public static ProfileCompany getInstance() {
		return instance;
	}
	
	public void insertCompany(int id, Company company){
		companyMap.put(id, company);
		Industry in = company.industry;
		in.insertCompany(company);
	}
}
